package com.zjw.touchscreen.listener;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHidDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import com.zjw.touchscreen.adapter.BluetoothSpinnerAdapter;
import com.zjw.touchscreen.bluetooth.BluetoothListItem;
import com.zjw.touchscreen.bluetooth.BluetoothUtils;
import com.zjw.touchscreen.config.RetrofitManager;
import com.zjw.touchscreen.http.ApiInterface;
import com.zjw.touchscreen.http.entity.BuryingPointEntity;
import com.zjw.touchscreen.http.entity.enums.BuryingPointTypeEnum;
import com.zjw.touchscreen.utils.UpdateUtils;
import lombok.SneakyThrows;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;

import static com.zjw.touchscreen.bluetooth.Constants.*;

public class ConnectClickListener implements View.OnClickListener {

    private Handler mainHandler = new Handler();

    private Spinner spinner;
    private Context context;
    private int state;

    public ConnectClickListener(Context context, Spinner spinner) {
        this.context = context;
        this.spinner = spinner;
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    @SuppressLint("MissingPermission")
    @Override
    public void onClick(View v) {
        v.setEnabled(false);
        closeConnect();
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                long now = System.currentTimeMillis();
                while (state != BluetoothHidDevice.STATE_DISCONNECTED) {
                    if (System.currentTimeMillis() - now > 1000 * 30) {
                        Toast.makeText(context, "蓝牙连接超时！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Thread.sleep(500);
                }
                Thread.sleep(1000);
                mainHandler.post(() -> v.setEnabled(true));
                BluetoothListItem bluetoothListItem = (BluetoothListItem) spinner.getSelectedItem();
                BluetoothUtils.setBluetoothDevice(bluetoothListItem.getBluetoothDevice());

                BluetoothUtils.getBluetoothDevice().createBond();
                //获取bluetoothHidDevice
                BluetoothUtils.getBluetoothAdapter().getProfileProxy(context, new BluetoothProfile.ServiceListener() {
                    @RequiresApi(api = Build.VERSION_CODES.P)
                    @Override
                    public void onServiceConnected(int profile, BluetoothProfile bluetoothProfile) {
                        if (profile != BluetoothProfile.HID_DEVICE) {
                            return;
                        }
                        BluetoothHidDevice bluetoothHidDevice = (BluetoothHidDevice) bluetoothProfile;
                        BluetoothUtils.setBluetoothHidDevice(bluetoothHidDevice);
                        BluetoothHidDevice.Callback callback = new BluetoothHidDevice.Callback() {
                            @Override
                            public void onAppStatusChanged(BluetoothDevice pluggedDevice, boolean registered) {
                                super.onAppStatusChanged(pluggedDevice, registered);
                                BluetoothUtils.isHidDeviceConnected = bluetoothHidDevice.connect(bluetoothListItem.getBluetoothDevice());
                            }

                            @Override
                            public void onGetReport(BluetoothDevice device, byte type, byte id, int bufferSize) {
                                super.onGetReport(device, type, id, bufferSize);
                            }

                            @Override
                            public void onSetReport(BluetoothDevice device, byte type, byte id, byte[] data) {
                                super.onSetReport(device, type, id, data);
                            }

                            @Override
                            public void onConnectionStateChanged(BluetoothDevice device, int state) {
                                BluetoothSpinnerAdapter bluetoothSpinnerAdapter = (BluetoothSpinnerAdapter) spinner.getAdapter();
                                List<BluetoothListItem> bluetoothListItems = bluetoothSpinnerAdapter.getBluetoothListItems();
                                BluetoothListItem bluetoothListItem = null;
                                for (BluetoothListItem listItem : bluetoothListItems) {
                                    if (listItem.getBluetoothDevice().equals(device)) {
                                        bluetoothListItem = listItem;
                                        break;
                                    }
                                }
                                if (bluetoothListItem == null) {
                                    return;
                                }
                                switch (state) {
                                    case BluetoothHidDevice.STATE_CONNECTED:
                                        bluetoothListItem.setStatus("已连接");
                                        //连接埋点
                                        new Thread(() -> {
                                            ApiInterface apiInterface = RetrofitManager.create(ApiInterface.class);
                                            BuryingPointEntity buryingPointEntity = new BuryingPointEntity();
                                            int apiLevel = Build.VERSION.SDK_INT;
                                            String versionName = Build.VERSION.RELEASE;
                                            String manufacturer = Build.MANUFACTURER;
                                            String model = Build.MODEL;
                                            String brand = Build.BRAND;
                                            String product = Build.PRODUCT;
                                            String hardware = Build.HARDWARE;
                                            buryingPointEntity.setApiLevel(apiLevel);
                                            buryingPointEntity.setSysVersion(versionName);
                                            buryingPointEntity.setManufacturer(manufacturer);
                                            buryingPointEntity.setModel(model);
                                            buryingPointEntity.setBrand(brand);
                                            buryingPointEntity.setProduct(product);
                                            buryingPointEntity.setHardware(hardware);
                                            buryingPointEntity.setType(BuryingPointTypeEnum.CONNECT_BLUETOOTH);
                                            Integer versionId = UpdateUtils.getVersionCode(context);
                                            buryingPointEntity.setAppVersionId(versionId);
                                            Call<ResponseBody> responseBodyCall = apiInterface.buryingPointAdd(buryingPointEntity);
                                            try {
                                                Response<ResponseBody> response = responseBodyCall.execute();
                                                int code = response.code();
                                                ResponseBody body = response.body();
                                                if (code == 200) {
                                                    if (body != null) {
                                                        String json = body.string();
                                                        Log.e("StateChanged: ", json);
                                                        body.close();
                                                    }
                                                }
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }).start();
                                        break;
                                    case BluetoothHidDevice.STATE_DISCONNECTED:
                                        bluetoothListItem.setStatus("已断开");
                                        break;
                                    case BluetoothHidDevice.STATE_CONNECTING:
                                        bluetoothListItem.setStatus("连接中");
                                        break;
                                    case BluetoothHidDevice.STATE_DISCONNECTING:
                                        bluetoothListItem.setStatus("断开中");
                                        break;
                                }
                                mainHandler.post(bluetoothSpinnerAdapter::notifyDataSetChanged);
                            }

                            @Override
                            public void onSetProtocol(BluetoothDevice device, byte protocol) {
                                super.onSetProtocol(device, protocol);
                            }
                        };
                        bluetoothHidDevice.registerApp(SDP_RECORD, inQos, outQos, Runnable::run, callback);
                    }

                    @Override
                    public void onServiceDisconnected(int profile) {

                    }
                }, BluetoothProfile.HID_DEVICE);
            }
        }).start();

    }

    @SuppressLint("MissingPermission")
    @RequiresApi(api = Build.VERSION_CODES.P)
    private void closeConnect() {
        BluetoothAdapter bluetoothAdapter = BluetoothUtils.getBluetoothAdapter();
        BluetoothHidDevice bluetoothHidDevice = BluetoothUtils.getBluetoothHidDevice();
        if (bluetoothHidDevice != null && bluetoothAdapter != null) {
            bluetoothHidDevice.unregisterApp();
            bluetoothAdapter.closeProfileProxy(BluetoothProfile.HID_DEVICE, bluetoothHidDevice);
        }
    }
}
